package org.dydl.controller.system;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.dydl.common.dto.ResponseMessage;
import org.dydl.model.system.SysUser;
import org.dydl.service.system.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

// TODO: Auto-generated Javadoc
//import lombok.Setter;

/**
 * The Class UserController.
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
	// @Reference
	/** The user service. */
	// @Setter
	@Autowired
	private ISysUserService userService;

	/**
	 * 获取用户
	 *
	 * @return the list
	 */
	@RequestMapping("/getUsers")
	public List<SysUser> student() {
		// todo 修改
		// return userService.getUsers();
		// return (List<SysUser>) userService.search(null).getData();
		return null;
	}

	/**
	 * 根据id获取用户
	 *
	 * @param id
	 *            the id
	 * @param model
	 *            the model
	 * @return the pet
	 */
	@RequestMapping(value = "get/{id}")
	public ResponseMessage getPet(@PathVariable Long id) {
		// return userService.getUser((Long)id);
		// return userService.search(new Search().addFilterEqual("id", id));
		return new ResponseMessage(false);
	}

	/**
	 * 获取当前用户信息
	 *
	 * @return the cur
	 */
	@RequestMapping("/getCurr")
	public UserDetails getCur() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		// 获取权限
		// Collection<? extends GrantedAuthority> authorities =
		// userDetails.getAuthorities();

		return userDetails;
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 *            the ids
	 * @return the boolean
	 */
	@RequestMapping("/delUser")
	public Boolean delete(long[] ids) {

		 if (null != ids && ids.length > 0) {
		 for (int i = 0; i < ids.length; i++) {
		
		 // 删除成功返回1
		 // userService.delete(userMap);
		 userService.delete(ids[i]);
		 }
		 return true;
		 } else {
		 return false;
		 }
	}

	/**
	 * 更新用户信息
	 *
	 * @param user
	 *            the user
	 * @return
	 */
//	@RequestMapping("/updUser")
//	public ResponseMessage update(@RequestBody SysUser user) {
//		// if (user.getId() == null) {
//		// user.setPassword(this.getDefaultPwd());
//		// }
//		// return userService.save(user);
//		return new ResponseMessage(false);
//	}
	
	@RequestMapping("/updUser")
	public void update(@RequestBody String user) {
		JSONObject jsStr = JSONObject.parseObject(user);
		long jsID = Integer.parseInt(jsStr.getString("id"));
		SysUser updUser = new SysUser();
		updUser.setId(jsID);
		updUser.setEmail(jsStr.getString("email"));
		updUser.setUserName(jsStr.getString("userName"));
		userService.save(updUser);
	}

	@RequestMapping("/resetPwd")
	public ResponseMessage resetPwd(int id) {
		// @SuppressWarnings("unchecked")
		// SysUser user = ((List<SysUser>) userService.search(new
		// Search().addFilterEqual("id", id)).getData()).get(0);
		// user.setPassword(this.getDefaultPwd());
		// return userService.save(user);
		return new ResponseMessage(false);
	}

	// private String getDefaultPwd() {
	// return MD5.encode("000000".getBytes());
	// }

	/**
	 * 
	 * 生成MD5简单方法 .
	 *
	 * @param str
	 *            the str
	 * @return the md5
	 */
	public StringBuilder getMD5(String str) {
		byte[] buf = str.getBytes();
		MessageDigest md5;
		StringBuilder sb = new StringBuilder();
		try {
			md5 = MessageDigest.getInstance("MD5");
			md5.update(buf);
			byte[] tmp = md5.digest();
			for (byte b : tmp) {
				sb.append(Integer.toHexString(b & 0xff));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return sb;
	}

	/**
	 * 添加新用户
	 *
	 * @param user
	 *            the user
	 * @throws UnsupportedEncodingException
	 *             the unsupported encoding exception
	 * @throws Exception
	 *             the exception
	 */
	@PreAuthorize("hasAuthority('ADMIN')")
	@RequestMapping("/newUser")
	public void create(@RequestBody SysUser newUser) throws UnsupportedEncodingException, Exception {
		 // 密码默认6个0
		newUser.setPassword(getMD5(newUser.getUserName() + "2016").toString());
		 // user.setEmail(email);
		 // 状态默认正常
		newUser.setStatus(true);
		 userService.save(newUser);
	}

	/**
	 * 分页查询
	 *
	 * @param page
	 *            the page
	 * @param rows
	 *            the rows
	 * @param keyword
	 *            the keyword
	 * @return the response message
	 */
//	@RequestMapping("/list")
//	public ResponseMessage list(int page, int rows, String keyword) {
//
//		 // 查询行数
//		 Search search = new Search();
//		 search.setPage(page - 1);
//		 search.setMaxResults(rows);
//		 if (null != keyword && !keyword.isEmpty()) {
//		 search.addFilterEqual("userName", keyword);
//		 }
//		 ResponseMessage responseMessage = userService.search(search);
//		 // 分页查询
//		
//		 return responseMessage;
//		return new ResponseMessage(false);
//	}
	
	@RequestMapping("/list")
	public ResponseMessage getEmployee(int page, int rows, String keyword) {
		ResponseMessage res = userService.getUserList(page, rows, keyword);
		return res;
	}

}
